// 认证状态管理
const authState = {
    isLoggedIn: false,
    user: null,
    token: null
};

// 切换登录模态框
function toggleLogin() {
    const modal = document.getElementById('loginModal');
    if (modal.style.display === 'flex') {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    } else {
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        hideRegisterModal();
    }
}

// 切换注册模态框
function toggleRegister() {
    const modal = document.getElementById('registerModal');
    if (modal.style.display === 'flex') {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    } else {
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        hideLoginModal();
    }
}

// 隐藏登录模态框
function hideLoginModal() {
    const modal = document.getElementById('loginModal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
}

// 隐藏注册模态框
function hideRegisterModal() {
    const modal = document.getElementById('registerModal');
    modal.style.display = 'none';
    document.body.style.overflow = '';
}

// 发送验证码
async function sendVerifyCode(phone) {
    try {
        // const response = await fetch('/api/auth/send-code', {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json'
        //     },
        //     body: JSON.stringify({ phone })
        // });
        // const result = await response.json();
        
        // 模拟发送成功
        console.log('验证码已发送');
        return true;
    } catch (error) {
        console.error('发送验证码失败:', error);
        return false;
    }
}

// 刷新图形验证码
function refreshCaptcha() {
    const captchaImg = document.querySelector('.captcha-img');
    if (captchaImg) {
        captchaImg.src = `path/to/captcha.jpg?t=${Date.now()}`;
    }
}

// 处理登录表单提交
async function handleLogin(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);

    try {
        // const response = await fetch('/api/auth/login', {
        //     method: 'POST',
        //     body: formData
        // });
        // const result = await response.json();

        // 模拟登录成功
        authState.isLoggedIn = true;
        authState.user = {
            id: '1',
            username: formData.get('username')
        };
        hideLoginModal();
        updateUIAfterLogin();
    } catch (error) {
        console.error('登录失败:', error);
    }
}

// 处理注册表单提交
async function handleRegister(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);

    try {
        // const response = await fetch('/api/auth/register', {
        //     method: 'POST',
        //     body: formData
        // });
        // const result = await response.json();

        // 模拟注册成功
        window.location.href = 'login.html';
    } catch (error) {
        console.error('注册失败:', error);
    }
}

// 更新登录后的UI
function updateUIAfterLogin() {
    const loginBtn = document.querySelector('.login-btn');
    if (loginBtn) {
        loginBtn.textContent = authState.user.username;
        loginBtn.onclick = null;
    }
}

// 初始化认证相关事件
function initAuth() {
    // 验证码发送按钮
    const verifyBtn = document.querySelector('.verify-btn');
    if (verifyBtn) {
        verifyBtn.addEventListener('click', async () => {
            const phoneInput = document.querySelector('input[type="tel"]');
            if (phoneInput && phoneInput.value) {
                const success = await sendVerifyCode(phoneInput.value);
                if (success) {
                    // 禁用按钮并开始倒计时
                    let countdown = 60;
                    verifyBtn.disabled = true;
                    const timer = setInterval(() => {
                        verifyBtn.textContent = `${countdown}秒后重试`;
                        countdown--;
                        if (countdown < 0) {
                            clearInterval(timer);
                            verifyBtn.disabled = false;
                            verifyBtn.textContent = '��送验证码';
                        }
                    }, 1000);
                }
            }
        });
    }

    // 图形验证码点击刷新
    const captchaImg = document.querySelector('.captcha-img');
    if (captchaImg) {
        captchaImg.addEventListener('click', refreshCaptcha);
    }

    // 登录表单提交
    const loginForm = document.querySelector('#loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', handleLogin);
    }

    // 注册表单提交
    const registerForm = document.querySelector('#registerForm');
    if (registerForm) {
        registerForm.addEventListener('submit', handleRegister);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initAuth); 